package com.ambow.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ambow.Entity.*;
import com.ambow.service.*;
import com.ambow.service.impl.*;


/**
 * Servlet implementation class StockReceiveServlet
 */
@WebServlet("/StockReceiveServlet")//教材入库
public class StockReceiveServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       TextBookService textBookService=new TextBookServiceImpl();
       SupplierService supplierService=new SupplierServiceImpl();
       CellService cellService=new  CellServiceImpl();
       StockReceiveService stockReceiveService=new StockReceiveServiceImpl();
       StockService stockService=new StockServiceImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		String status=request.getParameter("status");
		System.out.println("status"+status);
		if(status.equals("queryIsbn")) {
		  queryByIsbn(request,response);
		  
		}else if(status.equals("add")) {
			add(request,response);
		}else if(status.equals("queryOne")) {
			queryOne(request,response);
		}else if(status.equals("record")) {//查询教材入库表中的记录 
			queryRecord(request,response);
			
		}
		
		
	}
	
	
    private void queryRecord(HttpServletRequest request, HttpServletResponse response) {
    	String bookName=request.getParameter("bookName");//教材名
    	String startTime=request.getParameter("startTime");
    	String endTime=request.getParameter("endTime");
    	String supplierName=request.getParameter("supplierName");//供应商名称，模糊查询
    	if(bookName==""&&startTime==""&&endTime==""&&supplierName=="") {
    	 List<StockReceive>	 list=stockReceiveService.query("from StockReceive", null);
    	 request.setAttribute("list", list);
    	 System.out.println("list的长度：：：：：：：：：：：：：：：：：：：：：："+list.size());
    		}
    	else {
    	String[] param= {bookName, supplierName,startTime,endTime};
    	 List<StockReceive>	 list=stockReceiveService.query("from StockReceive stockReceive where stockReceive.textBook.name=? and stockReceive.supplier.name=? and  stockReceive.receiveDate>=? and stockReceive.receiveDate<=? ", param);
   	    request.setAttribute("list", list);
    	}
    	
		try {
			request.getRequestDispatcher("pages/module/storage/storage002/receive_query.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
  //添加到入库记录,同时也添加到库存中
	private void add(HttpServletRequest request, HttpServletResponse response) {
	 	try {
    	String amount=request.getParameter("amount");//入库的 数量
    	String remark=request.getParameter("remark");
    	String []checkbox=request.getParameterValues("checkbox");//选中入库的教材ID
    	String supplierId=request.getParameter("select");//供应商ID
    	String cellId=request.getParameter("cellid");//架位名
    	System.out.println("csadfggfhgjhkcheckbox:"+checkbox.length);
    	boolean f1=false,f2=false;
    	for (int i = 0; i < checkbox.length; i++) {
    		
    		  
    		
    		TextBook textBook=textBookService.queryOne(TextBook.class, Integer.valueOf(checkbox[i]));
        	Supplier supplier=supplierService.get(Supplier.class,Integer.valueOf(supplierId) );
    		 StockReceive stockReceive=new StockReceive();
    		 stockReceive.setAmount(Integer.valueOf(amount));
    		 if(request.getSession().getAttribute("op")!=null) {
    			 stockReceive.setOperator((Operator)request.getSession().getAttribute("op")); 
    		 }else {
    		 stockReceive.setOperator(null);//注意写操作人员，此外接收时需要存入库存
    		 }
    		 stockReceive.setReceiveDate(new Date());
    		 stockReceive.setRemark(remark);
    		 stockReceive.setSupplier(supplier);
    		 stockReceive.setTextBook(textBook);
    		 f1=stockReceiveService.add(stockReceive);
    		 
    		 Stock stockadd=new Stock();//库存
   		     stockadd.setAmount(Integer.valueOf(amount));
   		     stockadd.setCell(cellService.getOne(Cell.class, Integer.valueOf(cellId)));
   		     stockadd.setTextBook(textBook);
   		     List<Stock> list=stockService.Query("from Stock", null);
   		     //查询库存，如果遇到架位号和教材一致直接添加数量，更新，否则添加库存
   		     for (Stock stock : list) {
				if((stock.getTextBook().getId()==stockadd.getTextBook().getId())&&(stock.getCell().getId()==stockadd.getCell().getId())) {
					stock.setAmount(stock.getAmount()+stockadd.getAmount());
					f2=stockService.update(stock);
					 break;
					
				}
			}
   		     if(f2==false) { f2=stockService.add(stockadd);break;}
    		// if(f1&&f2) continue; 
    		 
		}
                     System.out.println("f1f2d21"+f1+f2);
			request.getRequestDispatcher("pages/module/storage/storage002/receive_query.jsp").forward(request, response);
			
      
    	} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
		   
	}

	//根据ISBN查询书籍,从接收的存库中查询，最后添加到库存中
	private void queryByIsbn(HttpServletRequest request, HttpServletResponse response) {
      
		 TextBook textBook=new TextBook();
		String isbn= request.getParameter("isbn");
		System.out.println("isbn..........."+isbn);
		String[] param= {isbn};
		List<TextBook> list=textBookService.query("from TextBook textbook where ISBN=?", param);
		request.setAttribute("list", list);
		request.setAttribute("isbn", isbn);
		try {
			request.getRequestDispatcher("pages/module/storage/storage002/get_receivebook.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	
		
		
	}
	private void queryOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer id=Integer.valueOf(request.getParameter("id"));
	    System.out.println("11wwwww"+id);
		TextBook textBook=textBookService.queryOne(TextBook.class, id);
		request.setAttribute("textbook", textBook);
		System.out.println("textbook>>>>>"+textBook);

	request.getRequestDispatcher("pages/module/storage/storage002/book_detail.jsp").forward(request, response);
		
		
	}

}
